package com.example.common.component;

import android.util.Log;


import com.example.common.control.ICallback;
import com.example.common.model.CaptchaServiceGenerateResp;
import com.example.common.model.Description;
import com.example.common.model.MyResponse;
import com.example.common.model.RsaApiCreateResp;
import com.example.common.model.SessionApiLoginResp;
import com.example.common.network.LoginRegisterReq;
import com.example.common.network.RetrofitServiceManager;
import com.example.common.utils.AesUtils;
import com.example.common.utils.RsaUtils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 登录注册组件，将登录注册接口实例化
 */
public class LoginCtrlCom{
    //登录和注册的操作请求实例
    private LoginRegisterReq loginRegisterReq;
    private static final String TAG="loginCtrlCom";
    private RSACtrlCom rsaCtrlCom;

    //构造函数
    public LoginCtrlCom(){
        rsaCtrlCom=new RSACtrlCom();
        loginRegisterReq= RetrofitServiceManager.getInstance().create(LoginRegisterReq.class);
    }


    /**
     * 加载验证码图片
     * @param iCallback
     */
    public void midmap(ICallback iCallback) {
        //获取Call请求
        Call<MyResponse<CaptchaServiceGenerateResp>> call = loginRegisterReq.getCaptcha();
        //发出请求
        call.enqueue(new Callback<MyResponse<CaptchaServiceGenerateResp>>() {
            @Override
            public void onResponse(Call<MyResponse<CaptchaServiceGenerateResp>> call, Response<MyResponse<CaptchaServiceGenerateResp>> response) {//处理响应数据
                if(response.isSuccessful()){//[200,300)
                    //获取响应数据主体
                    CaptchaServiceGenerateResp captcha=response.body().getData();
                    System.out.println(captcha.getId());
                    //获取验证码回调
                    iCallback.onSuccess(captcha);
                }else {
                    iCallback.onFailed("服务器错误");
                }
            }

            @Override
            public void onFailure(Call<MyResponse<CaptchaServiceGenerateResp>> call, Throwable t) {//请求失败处理
                iCallback.onFailed("网络错误");
            }
        });
    }

    /**
     * 校验验证码
     * @param id 验证码id
     * @param ans 用户输入的验证码结果
     * @param iCallback 回调函数
     */
    public void checkCaptcha(String id, String ans, ICallback iCallback) {
        //获取call请求
        Call<MyResponse<Boolean>> call=loginRegisterReq.postCaptcha(id, ans);
        //发出请求
        call.enqueue(new Callback<MyResponse<Boolean>>() {
            @Override
            public void onResponse(Call<MyResponse<Boolean>> call, Response<MyResponse<Boolean>> response) {
                if(response.body()!=null){
                    MyResponse<Boolean> checkCaptchaResult=response.body();
                    if (checkCaptchaResult.getCode()==500){
                        iCallback.onFailed(checkCaptchaResult.getErrmsg());
                    }else if(checkCaptchaResult.getCode()==200&&checkCaptchaResult.getData()){
                        iCallback.onSuccess(checkCaptchaResult.getData());
                    }else {
                        iCallback.onFailed("校验验证码——发生未知错误");
                    }
                }else{
                    iCallback.onFailed("校验验证码——body为null");
                }
            }

            @Override
            public void onFailure(Call<MyResponse<Boolean>> call, Throwable t) {
                iCallback.onFailed("校验验证码——请求失败");
            }
        });
    }

    /**
     * 注册
     * @param phoneNumber 手机号
     * @param password 密码
     * @param inviteCode 邀请码
     * @param iCallback 回调函数 返回类型Description
     */
    public void register(String phoneNumber, String password, String inviteCode, ICallback iCallback) {
        rsaCtrlCom.postRSA(new ICallback() {
            @Override
            public void onSuccess(Object response) {
                try {
                    RsaApiCreateResp RSA=(RsaApiCreateResp)response;
                    String publicKey =  new String(AesUtils.decrypt(Base64.getDecoder().decode(
                            RSA.getRsa().getBytes(StandardCharsets.UTF_8))
                    ), StandardCharsets.UTF_8);
                    // 请求体
                    Map<String, Object> params = new HashMap<>();
                    params.put("phoneNumber", phoneNumber);
                    params.put("password", password);
                    params.put("inviteCode",inviteCode);
                    // 加密
                    String data = RsaUtils.encrypt(params, publicKey);
                    //创建请求
                    Call<MyResponse<Description>> call=loginRegisterReq.postUser(RSA.getId(),data);
                    //发起请求
                    call.enqueue(new Callback<MyResponse<Description>>() {
                        @Override
                        public void onResponse(Call<MyResponse<Description>> call, Response<MyResponse<Description>> response) {
                            if(response.isSuccessful()){
                                MyResponse<Description> myResponse=response.body();
                                if(myResponse!=null){
                                    if(myResponse.getCode()==200){
                                        iCallback.onSuccess(myResponse.getData());
                                    }else {
                                        iCallback.onFailed(myResponse.getErrmsg());
                                    }
                                }else {
                                    iCallback.onFailed("响应体为空");
                                }
                            }else {
                                iCallback.onFailed("错误码500");
                            }
                        }

                        @Override
                        public void onFailure(Call<MyResponse<Description>> call, Throwable t) {
                            iCallback.onFailed(t.toString());
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String mes) {
                iCallback.onFailed(mes);
            }
        });
    }

    /**
     * 登录
     * @param phoneNumber 手机号
     * @param password 密码
     * @param iCallback 回调 返回类型 SessionApiLoginResp
     */
    public void login(String phoneNumber, String password, ICallback iCallback){
        rsaCtrlCom.postRSA(new ICallback() {
            @Override
            public void onSuccess(Object response) {
                try {
                    RsaApiCreateResp RSA=(RsaApiCreateResp)response;
                    String publicKey =  new String(AesUtils.decrypt(Base64.getDecoder().decode(
                            RSA.getRsa().getBytes(StandardCharsets.UTF_8))
                    ), StandardCharsets.UTF_8);
                    // 请求体
                    Map<String, Object> params = new HashMap<>();
                    params.put("phoneNumber", phoneNumber);
                    params.put("password", password);
                    // 加密
                    String data = RsaUtils.encrypt(params, publicKey);
                    //创建请求
                    Call<MyResponse<SessionApiLoginResp>> call=loginRegisterReq.postSession(RSA.getId(), data);

                    //发出请求
                    call.enqueue(new Callback<MyResponse<SessionApiLoginResp>>() {
                        @Override
                        public void onResponse(Call<MyResponse<SessionApiLoginResp>> call, Response<MyResponse<SessionApiLoginResp>> response) {
                            if(response.isSuccessful()){
                                MyResponse<SessionApiLoginResp> myResponse=response.body();
                                if(myResponse!=null){
                                    if(myResponse.getCode()==200){
                                        iCallback.onSuccess(myResponse.getData());
                                    }else {
                                        iCallback.onFailed(myResponse.getErrmsg());
                                    }
                                }else {
                                    iCallback.onFailed("响应体为空");
                                }
                            }else {
                                iCallback.onFailed("错误码500");
                            }
                        }

                        @Override
                        public void onFailure(Call<MyResponse<SessionApiLoginResp>> call, Throwable t) {
                            iCallback.onFailed("网络错误");
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailed(String mes) {
            }
        });


    }

    /**
     * 验证是否登录
     * @param token
     * @param iCallback
     */
    public void getSession(String token,ICallback iCallback){
        Call<MyResponse<Boolean>> call=loginRegisterReq.getSession(token);
        call.enqueue(new Callback<MyResponse<Boolean>>() {
            @Override
            public void onResponse(Call<MyResponse<Boolean>> call, Response<MyResponse<Boolean>> response) {
                if(response.isSuccessful()){
                    MyResponse<Boolean> myResponse=response.body();
                    if(myResponse!=null){
                        if(myResponse.getCode()==200){
                            //返回类型 Boolean
                            iCallback.onSuccess(myResponse.getData());
                        }
                    }else {
                        iCallback.onFailed("响应体为空");
                    }
                }else {
                    iCallback.onFailed("响应错误");
                }
            }

            @Override
            public void onFailure(Call<MyResponse<Boolean>> call, Throwable t) {
                iCallback.onFailed("网络错误");
            }
        });
    }
}
